﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
//using DevExpress.LocalizationCHS;
using DevExpress.Utils;
using DevExpress.XtraEditors.Controls;
using DevExpress.XtraGrid.Columns;
using DevExpress.XtraEditors.Repository;
using JsalesModel;
using DevExpress.XtraGrid.Views.Grid;
using DevExpress.XtraGrid.Views.Base;


namespace JSales.ModuleSystem
{
    public partial class UserManageForm : Form
    {
        public UserManageForm()
        {
            InitializeComponent();
        }

        public BindingSource bindingSource = new BindingSource();
        private string EditMode = null;

        private void CtrolINI()
        {
            barButtonAdd.Enabled = true;
            barButtonEdit.Enabled = true;
            barButtonDelete.Enabled = true;
            barButtonSave.Enabled = false;
            barButtonCancel.Enabled = false;

            textID.Enabled = false;
            textPSWD.Enabled = false;
            textUserName.Enabled = false;
            lookUpDept.Enabled = false;
            checkDisable.Enabled = false;

            gridView1.OptionsBehavior.Editable = false;
            gridView1.OptionsBehavior.AllowAddRows = DevExpress.Utils.DefaultBoolean.False;
            gridView1.OptionsView.NewItemRowPosition = NewItemRowPosition.None;
        }

        //private BindingList<TbDept> BindListdept= new BindingList<TbDept>(DeptClass.QueryActive());

        private void UserManageForm_Load(object sender, EventArgs e)
        {
            CtrolINI();
            // TODO: 这行代码将数据加载到表“jOrderDataSet.tbDept”中。您可以根据需要移动或删除它。
            //汉化界面
            // DevExpress.XtraGrid.Localization.GridLocalizer.Active = new DevExpress.LocalizationCHS.DevExpressXtraGridLocalizationCHS();
            // DevExpress.XtraTreeList.Localization.TreeListLocalizer.Active= new DevExpressXtraTreeListLocalizationCHS();
            //BindingList<TbUser> users= new BindingList<TbUser>(UsersClass.Query());
            //users.AllowNew = true;

            var dbConText = new JYEntities();
            bindingSource.DataSource = dbConText.TbUsers;
            gridControl1.DataSource = bindingSource;

            gridView1.Columns["DeptID"].FieldName = "DeptID";
            gridView1.Columns["DeptID"].Caption = "部门";
            RepositoryItemLookUpEdit lookup = new RepositoryItemLookUpEdit();
            lookup.DataSource = GlobalVar.GDepts.ToList();
            lookup.DisplayMember = "DeptName";
            lookup.ValueMember = "DeptID";
            lookup.PopulateColumns();
            gridView1.Columns["DeptID"].ColumnEdit = lookup;
            //gridView1.Columns["DeptID"].VisibleIndex = 3;

            gridView1.Columns["UserName"].FieldName = "UserName";
            gridView1.Columns["UserName"].Caption = "姓名";
            //gridView1.Columns["UserName"].VisibleIndex = 0;

            gridView1.Columns["LoginID"].FieldName = "LoginID";
            gridView1.Columns["LoginID"].Caption = "登录名";
            //gridView1.Columns["LoginID"].VisibleIndex = 1;

            gridView1.Columns["PSWD"].Visible = false;
            gridView1.Columns["PSWD"].FieldName = "PSWD";
            gridView1.Columns["PSWD"].Caption = "密码";
            //gridView1.Columns["PSWD"].VisibleIndex = 2;
            RepositoryItemTextEdit edit= new RepositoryItemTextEdit();
            gridView1.Columns["PSWD"].ColumnEdit = edit;
            edit.PasswordChar = '*';

            gridView1.Columns["IsDeleted"].FieldName = "IsDeleted";
            gridView1.Columns["IsDeleted"].Caption = "是否已删除";
            //gridView1.Columns["isDeleted"].VisibleIndex = 4;

            //隐藏如下列
            gridView1.Columns["SecLevel"].Visible = false;
            gridView1.Columns["SecLevel"].FieldName = "SecLevel";
            gridView1.Columns["SecLevel"].Caption = "安全级别";

            gridView1.Columns["CreationDate"].FieldName = "CreationDate";
            gridView1.Columns["CreationDate"].Visible = false;
            gridView1.Columns["CreationDate"].Caption = "创建日期";
            gridView1.Columns["LastEditDate"].FieldName = "LastEditDate";
            gridView1.Columns["LastEditDate"].Visible = false;
            gridView1.Columns["LastEditDate"].Caption = "最后更新日期";
            gridView1.Columns["LoginID"].FieldName = "LoginID";
            gridView1.Columns["LoginID"].Visible = false;
            gridView1.Columns["LoginID"].Caption = "登录名";
            gridView1.Columns["UserID"].FieldName = "UserID";
            gridView1.Columns["UserID"].Visible = false;
            gridView1.Columns["UserID"].Caption = "ID";
            
            lookUpDept.Properties.DataSource = GlobalVar.GDepts.ToList();
            lookUpDept.Properties.ValueMember = "DeptID";
            lookUpDept.Properties.DisplayMember = "DeptName";
            lookUpDept.Properties.PopulateColumns();
            lookUpDept.Properties.Columns["DeptName"].Caption = "部门";
            lookUpDept.Properties.Columns["UpDept"].Visible = false;
            lookUpDept.Properties.Columns["DeptID"].Visible = false;
            lookUpDept.Properties.Columns["Isdeleted"].Visible = false;
            lookUpDept.Properties.Columns["LastEditDate"].Visible = false;
            lookUpDept.Properties.Columns["CreationDate"].Visible = false;
            lookUpDept.Properties.Columns["VLeft"].Visible = false;
            lookUpDept.Properties.Columns["VRight"].Visible = false;  
        }
        
        private void GridView1InitNewRow(object sender, DevExpress.XtraGrid.Views.Grid.InitNewRowEventArgs e)
        {
            DevExpress.XtraGrid.Views.Grid.GridView view = sender as DevExpress.XtraGrid.Views.Grid.GridView;
            view.SetRowCellValue(e.RowHandle, view.Columns["UserName"], "");
            view.SetRowCellValue(e.RowHandle, view.Columns["IsDeleted"],false);
            this.gridView1.UpdateCurrentRow();
            //var user = new TbUser();
            //user.UserName=gridView1.
        }
        
        private void BarButtonAddItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            EditMode = "Add";

            barButtonSave.Enabled = true;
            barButtonCancel.Enabled = true;
            barButtonEdit.Enabled = false;
            barButtonDelete.Enabled = false;
            barButtonAdd.Enabled = false;

            textUserName.Enabled = true;
            textPSWD.Enabled = true;
            lookUpDept.Enabled = true;

            textID.Text = null;
            textPSWD.Text = null;
            textUserName.Text = null;
            lookUpDept.EditValue = null;
            checkDisable.EditValue = null;

        }

        private void barButtonEdit_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            EditMode = "Edit";

            barButtonSave.Enabled = true;
            barButtonCancel.Enabled = true;
            barButtonEdit.Enabled = false;
            barButtonDelete.Enabled = false;
            barButtonAdd.Enabled = false;

            textUserName.Enabled = true;
            textPSWD.Enabled = true;
            lookUpDept.Enabled = true;
        }

        private void barButtonSave_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            var dbConText = new JYEntities();
            if (!(string.IsNullOrEmpty(textPSWD.Text) || string.IsNullOrEmpty(textUserName.Text) || string.IsNullOrEmpty(lookUpDept.EditValue.ToString())))
            {
                switch (EditMode)
                {
                    case "Edit":
                        {
                            IQueryable<TbUser> users = from i in dbConText.TbUsers
                                                       where i.UserID == Convert.ToInt32(textID.Text)
                                                       select i;
                            if (users.Any())
                            {
                                TbUser user = users.FirstOrDefault();
                                user.UserName = textUserName.Text;
                                user.LoginID = textUserName.Text;
                                user.PSWD = textPSWD.Text;
                                user.DeptID = int.Parse(lookUpDept.EditValue.ToString());
                                dbConText.SaveChanges();
                            }
                            break;
                        }
                    case "Add":
                        {
                            TbUser user = new TbUser();
                            user.UserName = textUserName.Text;
                            user.LoginID = textUserName.Text;
                            user.PSWD = textPSWD.Text;
                            user.DeptID = Convert.ToInt32(lookUpDept.EditValue.ToString());
                            dbConText.Add(user);
                            dbConText.SaveChanges();
                            break;
                        }
                }
            UserManageForm_Load(sender,e);
            CtrolINI();
            }
            else
            {
                MessageBox.Show("用户名、密码、部门不能为空！");
            }
        }

        private void barButtonDelete_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            if (!string.IsNullOrEmpty(textID.Text))
            {
                var dbConText = new JYEntities();
                IQueryable<TbUser> users = from i in dbConText.TbUsers
                                           where i.UserID == Convert.ToInt32(textID.Text)
                                           select i;
                if (users.Any())
                {
                    TbUser user = users.FirstOrDefault();
                    user.IsDeleted = true;
                    dbConText.SaveChanges();
                    UserManageForm_Load(sender,e);
                }
            }
            else
            {
                MessageBox.Show("请先选择用户！");
            }
        }

        private void barButtonCancel_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            CtrolINI();
        }
        
        private void gridView1_ValidateRow(object sender, ValidateRowEventArgs e)
        {
            GridView view = sender as GridView;
            GridColumn DeptColumn = view.Columns["DeptID"];
            if (view.GetRowCellValue(e.RowHandle, DeptColumn)==DBNull.Value)
            {
                e.Valid = false;
                view.SetColumnError(DeptColumn, "部门不能为空");
            }
        }

        private void gridView1_InvalidRowException(object sender, InvalidRowExceptionEventArgs e)
        {
            e.ExceptionMode = ExceptionMode.NoAction;
        }

        private void gridView1_InvalidValueException(object sender, InvalidValueExceptionEventArgs e)
        {

        }   


        private void gridView1_RowClick(object sender, RowClickEventArgs e)
        {
            textID.DataBindings.Clear();
            textID.DataBindings.Add("Text", bindingSource, "UserID");

            textUserName.DataBindings.Clear();
            textUserName.DataBindings.Add("Text", bindingSource, "UserName");

            textPSWD.DataBindings.Clear();
            textPSWD.DataBindings.Add("Text", bindingSource, "PSWD");

            checkDisable.DataBindings.Clear();
            checkDisable.DataBindings.Add("Checked", bindingSource, "IsDeleted");

            int selectedHandle;
            selectedHandle = gridView1.GetSelectedRows()[0];
            lookUpDept.EditValue = int.Parse(gridView1.GetRowCellValue(selectedHandle, "DeptID").ToString());

            gridView1.RefreshData();
        }


    }
}
